﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataLib.Accounts.Bus;
using System.Data;
using DataLib.Common;

namespace Ewts.Storage
{
    public partial class CJOApply : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Session["UserInfo"] == null)
                {

                    Response.Redirect("/Accounts/Login.aspx");
                    return;
                }
               
                //参数为LoadNumID
                ListItem item = new ListItem();
                item.Text = "--请选择--";
                item.Value = "";
                DataLib.BLL.City bllCity = new DataLib.BLL.City();

                // 处理地
                ddlWasteDisposePlace.DataSource = bllCity.GetList("flag1='02'");
                ddlWasteDisposePlace.DataTextField = "cityname";
                ddlWasteDisposePlace.DataValueField = "cityname";
                ddlWasteDisposePlace.DataBind();
                ddlWasteDisposePlace.Items.Insert(0, item);

                
                if (Request["RelationID"] != null && Request["RelationID"].ToString().Trim() != "")
                {
                    DataLib.Model.ProjectsRelation prModel = new DataLib.Model.ProjectsRelation();
                    DataLib.BLL.ProjectsRelation prBll = new DataLib.BLL.ProjectsRelation();
                    prModel = prBll.GetModel(int.Parse(Request["RelationID"].Trim()));
                    hidRelID.Value = prModel.id.ToString();
                    if (Request["LoadID"] != null && Request["LoadID"].ToString().Trim() != "" && Request["LoadID"].ToString().Trim() !="0")
                {

                        BindByLoad(int.Parse(Request["LoadID"].Trim()),prModel);  
                }
                    BindbyRelid((int)prModel.id);
                     
                }
                else
                {
                    Response.Redirect("~/Storage/MyCustomerList.aspx");
                }

                //业务员
                    // this.txtSaleman.Text = curUser.UserName;

                          
                txtNoticeDate.Text = DateTime.Now.ToString();
            }
        }

        #region 加载数据
        /// <summary>
        /// 通过LoadNumID绑定数据
        /// </summary>
        /// <param name="LoadID">页面参数LoadNumID</param>
        protected void BindByLoad(int loadID,DataLib.Model.ProjectsRelation prmodel)
        {
            DataLib.Model.LoadNum loadNumModel = new DataLib.BLL.LoadNum().GetModel(loadID);
            DataLib.Model.ServerPoint spmodel = new DataLib.BLL.ServerPoint().GetModel((int)prmodel.ServerPointID);
            if (loadNumModel.customerid != 0 && loadNumModel.customerid.ToString().Trim() != "" && loadNumModel.addressid != null)
            {
                DataLib.Model.Cumtomer customerModel = new DataLib.BLL.Cumtomer().GetModel((int)loadNumModel.customerid);
                if (spmodel.Cjoperson_show != null && spmodel.Cjoperson_show.Trim() != "" && spmodel.Cjoperson_show.IndexOf("/") >= 0)
                {
                    string[] arr = spmodel.Cjoperson_show.Split('/');
                    txtSaleman.ToolTip = arr[0];
                    txtSaleman.Text = arr[1];
                }

                //DataLib.Model.CumtomerAddress cumAddrModel = new DataLib.Model.CumtomerAddress();
                //DataLib.BLL.CumtomerAddress bllAdd = new DataLib.BLL.CumtomerAddress();
                //hl 2013 11 15
                if (Request["RelationID"] != null && Request["RelationID"].ToString().Trim() != "")
                {
                    int rid = int.Parse(Request["RelationID"].ToString());
                    DataLib.Model.ProjectsRelation prModel = new DataLib.Model.ProjectsRelation();
                    DataLib.BLL.ProjectsRelation prBll = new DataLib.BLL.ProjectsRelation();
                    prModel = prBll.GetModel(rid);
                  
                    if (prModel != null)
                	{
                        BindbyRelid((int)prModel.id);
	                }
                   // hidAddID.Value = rid.ToString();
                   // cumAddrModel = bllAdd.GetModel(int.Parse(addid));
                }
                else
                {
                    //cumAddrModel = bllAdd.GetModel((int)loadNumModel.addressid);
                }
                  
                string[] newWaste = loadNumModel.RubbishType.Split(';');
                for (int i = 0; i < newWaste.Length; i++)
                {
                    if (newWaste[i] == cbWasteName1.Text)
                        cbWasteName1.Checked = true;
                    //if (newWaste[i] == cbWasteName2.Text)
                    //    cbWasteName2.Checked = true;
                    //if (newWaste[i] == cbWasteName3.Text)
                    //    cbWasteName3.Checked = true;
                    if (newWaste[i] == cbWasteName4.Text)
                        cbWasteName4.Checked = true;
                    if (newWaste[i] == cbWasteName5.Text)
                        cbWasteName5.Checked = true;
                    if (newWaste[i] == cbWasteName6.Text)
                        cbWasteName6.Checked = true;
                }
                
                txtLoadNum.Text = loadNumModel.loadnum;
                txtCJO.Text = Code.NumGeneration.GetSerialNum(loadNumModel.loadnum, "CJO");
                txtGoodsInfo.Text = loadNumModel.goodsInfo;

                ddlWasteDisposePlace.SelectedValue = loadNumModel.Rubbisharea;
                //txtCustomerCode.Text = customerModel.customercode;
                //txtCompany.Text = customerModel.companyname;
                hidLoadID.Value = loadID.ToString();
                string[] collectDate = loadNumModel.collectdate.ToString().Split(' ');
                txtCollectDate.Text = collectDate[0];
                txtCollectTime.Text = collectDate[1];
            }
        }

        /// <summary>
        /// 根据项目地址ID绑定相关数据
        /// </summary>
        /// <param name="relfid">项目地址ID</param>
        protected void BindbyRelid(int relfid)
        {
            DataLib.Model.ProjectsRelation rmodel = new DataLib.BLL.ProjectsRelation().GetModel(relfid);
            DataLib.Model.Project pmodel = new DataLib.BLL.Project().GetModel((int)rmodel.ProjectID);

            DataLib.Model.ServerPoint spmodel = new DataLib.BLL.ServerPoint().GetModel((int)rmodel.ServerPointID);

 
            DataLib.Model.CumtomerAddress cumAddrModel = new DataLib.BLL.CumtomerAddress().GetModel((int)rmodel.AddressID);
            DataLib.Model.Cumtomer customerModel = new DataLib.BLL.Cumtomer().GetModel((int)pmodel.CustomerID);

            txtCustomerCode.Text = pmodel.CustomerNum;
            txtCompany.Text = customerModel.companyname; ;
            txtCustomerContactor.Text = cumAddrModel.linkman;
            txtCustomerPhoneNum.Text = cumAddrModel.phone;
            txtCollectAddress.Text = rmodel.AddresssName;

            //cjo显示业务员
            if (spmodel.Cjoperson_show != null && spmodel.Cjoperson_show != "" && (spmodel.Cjoperson_show.IndexOf('/') >= 1 || spmodel.Cjoperson_show.IndexOf('@') >= 1))
            {
                char[] carr = { '/', '@' };
                txtSaleman.ToolTip = spmodel.Cjoperson_show.Split(carr)[0];
                txtSaleman.Text = spmodel.Cjoperson_show.Split(carr)[1];
            }
            
             txtLoadBelong.Value = pmodel.belongAddress;
        }
        #endregion

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            //录入的数据格式判断
            string strErr = ForEstimat();
            if(strErr != "")
            {
                MessageBox.Show(this, strErr);
                return;
            }
              

            DataLib.Model.LoadNum lModel = new DataLib.Model.LoadNum();
             DataLib.Model.Cjo cModel = new DataLib.Model.Cjo();
            DataLib.Model.VehicleRequire vModel = new DataLib.Model.VehicleRequire();
            lModel = GetLoadModel();
            cModel = GetCjoModel((int)lModel.id,lModel.loadnum);
            vModel = GetVehModel();

            cModel.belogcity = lModel.belongarea;
            cModel.graphiccity = lModel.Rubbisharea;
            cModel.loadnum = lModel.loadnum;
            
            DataLib.BLL.CJOItem bll = new DataLib.BLL.CJOItem();
            int loadid = bll.InsertCjoItem(lModel, cModel, vModel);

            try
            {
                if (loadid > 0)
                {
                    if (hidtyz.Value == "退运" || hidtyz.Value=="直销")
                    {
                        Sall(loadid);
                    }
                    DataLib.Common.MessageBox.ShowAndRedirect(Page, "Load号：" + lModel.loadnum + "；CJO号：" + cModel.cjono, "/RDLC/CjoReport.aspx?cjoid=" + bll.GetCjoId(loadid).ToString());
                }

            }
            catch (Exception ex)
            {
                DataLib.Common.MessageBox.Show(this, ex.Message);
            }
        }

        #region 验证
        /// <summary>
        /// 验证
        /// </summary>
        /// <returns>提示</returns>
        protected string ForEstimat()
        {
            string strErr = "";
            //if(!PageValidate.IsNumber(txtLoadNum.Text))
            //{
            //    strErr += "请勿自行修改LoadNum！\\n";
            //}
            //if (!PageValidate.IsNumber(txtCJO.Text))
            //{
            //    strErr += "请勿自行修改CJO！\\n";
            //}
          
            if (!PageValidate.IsDateTime(txtNoticeDate.Text))
            {
                strErr += "通知日期必须输入且必须为日期格式数据！\\n";
            }
            if (!PageValidate.IsDateTime(txtCollectDate.Text))
            {
                strErr += "收货日期必须输入且必须为日期格式数据！\\n";
            }
            if (!PageValidate.IsDateTime(txtCollectTime.Text))
            {
                strErr += "收货时间必须为时间格式数据！\\n";
            }
            if (txtCustomerCode.Text.Trim().Length == 0)
            {
                strErr += "客户编号不能为空！\\n";
            }
            if (txtCompany.Text.Trim().Length == 0)
            {
                strErr += "客户名称不能为空！\\n";
            }
            if (txtCollectAddress.Text.Trim().Length == 0)
            {
                strErr += "收货地址不能为空！\\n";
            }
            if (txtCustomerContactor.Text.Trim().Length == 0)
            {
                strErr += "客户联系人不能为空！\\n";
            }
            if (hidbussinesstype.Value == "") {
                strErr += "请选择业务类型\\n";
            }
            if (ddlWasteDisposePlace.SelectedValue == "")
            {
                strErr += "请选择处理地";
            }
            //if(!PageValidate.IsPhone(txtCustomerPhoneNum.Text))
            //{
            //    strErr += "客户联系方式不能为空且必须为数字！\\n";
            //}
            if (txtWorkerCount.Text != "" && txtWorkerCount.Text != null)
            {
                if (!PageValidate.IsNumber(txtWorkerCount.Text))  //根据需求，工人数，预计件数，货物重量可不填  2013.04.17 梁玲  
                {
                    strErr += "工人数不能为空且必须为数字！\\n";
                }
            }
            if (txtGoodsCount.Text != "" && txtGoodsCount.Text != null)
            {
                if (!PageValidate.IsNumber(txtGoodsCount.Text))
                {
                    strErr += "预计件数必须为数字！\\n";
                }
            }
            if (txtGoodsWeight.Text != "" && txtGoodsWeight.Text != null)
            {
                if (!PageValidate.IsNumber(txtGoodsWeight.Text))
                {
                    strErr += "货物重量必须为数字！\\n";
                }
            }
            if (cbMaternRequire1.Checked == false && cbMaternRequire2.Checked == false && cbMaternRequire3.Checked == false)
            {
                strErr += "请选择物料状态！\\n";
            }
            if (cbPeculiarRequire1.Checked == false && cbPeculiarRequire2.Checked == false && cbPeculiarRequire3.Checked == false && cbPeculiarRequire4.Checked == false && cbPeculiarRequire5.Checked == false && cbPeculiarRequire6.Checked == false)
            {
                strErr += "请选择特殊要求！\\n";
            }
            if (cbWasteName1.Checked == false  && cbWasteName4.Checked == false && cbWasteName5.Checked == false && cbWasteName6.Checked == false)
            {
                strErr += "请选择废弃物类型！\\n";
            }
            if (txtOtherCost.Text!="" && txtOtherCost.Text!=null)
            {
                if (!PageValidate.IsNumber(txtOtherCost.Text))
                {
                    strErr += "其他费用必须为数字！\\n";
                }
            }
            if (rblPayType1.Checked == false && rblPayType2.Checked == false && rblPayType3.Checked == false && rblPayType4.Checked == false)
            {
                strErr += "必须选择结算方式";
            }
            return strErr;
        }
        #endregion

        #region 3个对象值

        /// <summary>
        /// 取得LoadNum值
        /// </summary>
        /// <returns></returns>
        public DataLib.Model.LoadNum GetLoadModel()
        {

            int cusAddrID = (int)new DataLib.BLL.ProjectsRelation().GetModel(int.Parse(hidRelID.Value)).AddressID;
            DataLib.Model.CumtomerAddress addModel = new DataLib.BLL.CumtomerAddress().GetModel(cusAddrID);
            DataLib.Model.Cumtomer cumModel = new DataLib.BLL.Cumtomer().GetModel(addModel.customerid);
            DataLib.Model.LoadNum lModel = new DataLib.Model.LoadNum();
            if (hidLoadID.Value == "0" || hidLoadID.Value==null ||hidLoadID.Value=="")
            {
                lModel.id = 0;
                lModel.addressid = int.Parse(Request["RelationID"].ToString());
                lModel.belongarea = txtLoadBelong.Value;
                lModel.collectdate = DateTime.Parse(this.txtCollectDate.Text + " " + txtCollectTime.Text);
                lModel.customerid = cumModel.id;
                lModel.finishWeight = 0;
                lModel.goodsInfo = txtGoodsInfo.Text;
                lModel.loadnum = Code.NumGeneration.GetSerialNum("86", "LoadNum");

                lModel.Rubbisharea = ddlWasteDisposePlace.SelectedValue;
                lModel.RubbishType = GetRubbishType();
                lModel.saleman = txtSaleman.ToolTip;
                lModel.status = 1;
                lModel.totalWeight = 0;
                lModel.Memo = txtmemo.Text;
            }
            else
            {
                lModel = new DataLib.BLL.LoadNum().GetModel(int.Parse(hidLoadID.Value));
            }
            return lModel;
        }
        /// <summary>
        /// 获取cjo对象
        /// </summary>
        /// <param name="loadNumID"></param>
        /// <returns></returns>
        public DataLib.Model.Cjo GetCjoModel(int loadNumID, string loadnum)
        {
            DataLib.Model.Cjo cModel = new DataLib.Model.Cjo();
            cModel.loadnumid = loadNumID;
            cModel.cjono = Code.NumGeneration.GetSerialNum(loadnum, "CJO");
            cModel.bussinesstype = hidbussinesstype.Value;
            //退运直销特殊处理
            if (hidtyz.Value == "退运")
            {
                cModel.status = -1;
            }
            else if (hidtyz.Value == "直销")
            {
                cModel.status = -2;
            }
            else if (hidtyz.Value == "服务")
            {
                cModel.status = 1;  //待派车
            }
            else if (txtCollectAddress.Text.Trim().IndexOf("自送") >= 0)
            {
                cModel.status = 2;  //等称重
            }
            else
            {
                cModel.status = 1;
            }
            cModel.istyz = hidtyz.Value;
            cModel.createtime = DateTime.Parse(txtNoticeDate.Text);
            cModel.islocal = true;

            User curUser = new User();
            //新增Cjo数据并得到其ID CJO状态改为待派车
            if (Session["UserInfo"] != null)
            {
                curUser = (User)Session["UserInfo"];
                cModel.operman = curUser.UserName;
            }
           
            if (txtGoodsWeight.Text == null || txtGoodsWeight.Text == "")
            {
                cModel.predictweight = 0;
            }
            else
                cModel.predictweight = decimal.Parse(txtGoodsWeight.Text);
            cModel.cjocolldate = DateTime.Parse(this.txtCollectDate.Text + " " + txtCollectTime.Text);
            cModel.addid = int.Parse(hidRelID.Value);
            cModel.goodsdesc = txtGoodsInfo.Text;
            cModel.rubbType = GetRubbishType();
            cModel.id = 0;

            int cusAddrID = (int)new DataLib.BLL.ProjectsRelation().GetModel(int.Parse(hidRelID.Value)).AddressID;
            DataLib.Model.CumtomerAddress addModel = new DataLib.BLL.CumtomerAddress().GetModel(cusAddrID);
            DataLib.Model.Cumtomer cumModel = new DataLib.BLL.Cumtomer().GetModel(addModel.customerid);
            cModel.customerid = cumModel.id.ToString();
            cModel.customercode = cumModel.customercode;
            cModel.customername = cumModel.companyname;
            cModel.cjoadd = txtCollectAddress.Text;
            cModel.cjolinkman = txtCustomerContactor.Text;
            cModel.cjophone = txtCustomerPhoneNum.Text;
            cModel.cjoremark = txtmemo.Text;

            return cModel;
        }

        /// <summary>
        /// 获取VehicleRequire对象
        /// </summary>
        /// <returns></returns>
        public DataLib.Model.VehicleRequire GetVehModel()
        {
            DataLib.Model.VehicleRequire vModel = new DataLib.Model.VehicleRequire();
   
            string payType = "";

            if (rblPayType1.Checked)
                payType = rblPayType1.Text;
            if (rblPayType2.Checked)
                payType = rblPayType2.Text;
            if (rblPayType3.Checked)
                payType = rblPayType3.Text;
            if (rblPayType4.Checked)
                payType = rblPayType4.Text;
          
            if (txtWorkerCount.Text == null || txtWorkerCount.Text == "")
            {
                vModel.workercount = "0";
            }
            else
                vModel.workercount = txtWorkerCount.Text;

            vModel.clearingform = payType;
            if (txtGoodsCount.Text == "" || txtGoodsCount.Text == null)
            {
                vModel.numberestimate = 0;
            }
            else
                vModel.numberestimate = decimal.Parse(txtGoodsCount.Text);

            vModel.maternrequire = GetMaternRequire();
            vModel.samplingrequire = GetSamplingRequire();
            vModel.peculiarrequire = GetPeculiarRequire();
            vModel.otherrequire = txtOtherRequire.Text;
            vModel.other = txtVehiRequire.Text;
            vModel.othervrequire = txtqt.Text;
            vModel.vehiclecount = 0; //暂时没用
            vModel.id = 0;
            try
            {
                vModel.othercost = decimal.Parse(txtOtherCost.Text.Trim());
            }
            catch
            {
                vModel.othercost = 0;
            }

            vModel.tools = GetToolsStr();
            return vModel;
        }
        #endregion

        #region 多控件值录入
        /// <summary>
        /// 获取废弃物类型
        /// </summary>
        /// <returns></returns>
        public string GetRubbishType()
        {
            string waste = "";

            if (cbWasteName1.Checked)
                waste += cbWasteName1.Text + ";";
            //if (cbWasteName2.Checked)
            //    waste += cbWasteName2.Text + ";";
            //if (cbWasteName3.Checked)
            //    waste += cbWasteName3.Text + ";";
            if (cbWasteName4.Checked)
                waste += cbWasteName4.Text + ";";
            if (cbWasteName5.Checked)
                waste += cbWasteName5.Text + ";";
            if (cbWasteName6.Checked)
                waste += cbWasteName6.Text + ";";
            return waste;
        }

        /// <summary>
        /// 获取工具要求
        /// </summary>
        /// <returns></returns>
        private string GetToolsStr()
        {
            string toolsReq = "";
            if (rbTools1.Checked == true)
                toolsReq += rbTools1.Text + "," + txtTools1.Text + ";";
            if (rbTools2.Checked == true)
                toolsReq += rbTools2.Text + "," + txtTools2.Text + ";";
            if (rbTools3.Checked == true)
                toolsReq += rbTools3.Text + "," + txtTools3.Text + ";";
            if (rbTools4.Checked == true)
                toolsReq += rbTools4.Text + "," + txtTools4.Text + ";";
            if (rbTools5.Checked == true)
                toolsReq += rbTools5.Text + "," + txtTools5.Text + ";";
            if (rbTools6.Checked == true)
                toolsReq += rbTools6.Text + "," + txtTools6.Text + ";";
            return toolsReq;
        }

        /// <summary>
        /// 物料状态选择
        /// </summary>
        /// <returns></returns>
        private string GetMaternRequire()
        {
            string matern = "";
            if (cbMaternRequire1.Checked)
                matern += cbMaternRequire1.Text + ";";
            if (cbMaternRequire2.Checked)
                matern += cbMaternRequire2.Text + ";";
            if (cbMaternRequire3.Checked)
                matern += cbMaternRequire3.Text + ";";
            return matern;
        }

        /// <summary>
        /// 获取采样要求
        /// </summary>
        /// <returns></returns>
        public string GetSamplingRequire()
        {
            string sampling = "";
            if (rblSamplingRequire1.Checked)
                sampling = rblSamplingRequire1.Text;
            if (rblSamplingRequire2.Checked)
                sampling = rblSamplingRequire2.Text;
            if (rblSamplingRequire3.Checked)
                sampling = rblSamplingRequire3.Text;
            return sampling;
        }

        /// <summary>
        /// 特殊要求
        /// </summary>
        /// <returns></returns>
        public string GetPeculiarRequire()
        {
            string peculiar = "";

            if (cbPeculiarRequire1.Checked)
                peculiar += cbPeculiarRequire1.Text + ";";
            if (cbPeculiarRequire2.Checked)
                peculiar += cbPeculiarRequire2.Text + ";";
            if (cbPeculiarRequire3.Checked)
                peculiar += cbPeculiarRequire3.Text + ";";
            if (cbPeculiarRequire4.Checked)
                peculiar += cbPeculiarRequire4.Text + ";";
            if (cbPeculiarRequire5.Checked)
                peculiar += cbPeculiarRequire5.Text + ";";
            if (cbPeculiarRequire6.Checked)
                peculiar += cbPeculiarRequire6.Text + ";";
            return peculiar;
        }
        #endregion

        /// <summary>
        /// 退运直销直接生成财务数据
        /// </summary>
        public void Sall(int loadid)
        {
            DataLib.Model.FinaceData fModel = new DataLib.Model.FinaceData();
            DataLib.Model.LoadNum lModel = new DataLib.BLL.LoadNum().GetModel(loadid);
            DataLib.Model.Cumtomer cumModel = new DataLib.BLL.Cumtomer().GetModel((int)lModel.customerid);
          
            fModel.LoadNumID = lModel.id;
            fModel.LoadNumNo = lModel.loadnum;
            fModel.CustomerID = lModel.customerid;
            fModel.CustomerCode = cumModel.customercode;
            fModel.CustomerName = cumModel.companyname;
            fModel.CollecInvoiceDate = "零结算";
            fModel.CollecMoneyDate = "零结算";
            fModel.InvoiceDate = "零结算";
            fModel.PayDate = "零结算";
            DataLib.BLL.FinaceData fdBll = new DataLib.BLL.FinaceData();
           if(!fdBll.ExistsByLoad(loadid))
                fdBll.Add(fModel);
        }
    }
}